<?php

class Core_Action_Admin_System_Mail_Template_Edit extends Action_Admin
{

	public function execute($request, $initial = FALSE, $script = NULL)
	{
		if ($initial)
		{
			Agilet::setVar('breadcrum', array(
				array(
					'url' => 'admin/system',
					'label' => 'System'
				),
				array(
					'url' => 'admin/system/mail',
					'label' => 'Mail'
				),
				array(
					'url' => 'admin/system/mail/template',
					'label' => 'Template'
				),
				array(
					'url' => 'admin/system/mail/template/edit',
					'label' => 'Edit'
				)
			));

		}

		$table = Model::getTable('core/mail/translation');

		$lang = $request -> getParam('lang', 'en');

		$id = $request -> getParam('id');

		$select = $table -> select() -> where('template_id=?', $id) -> where('language=?', $lang);

		$item = $table -> fetchRow($select);
		
		$form = Form::factory('core/admin/mail/template');

		if ($request -> isGet() && $item)
		{
			$form -> setData($item -> toArray());
		}

		if ($request -> isPost() && $form -> isValid($_POST))
		{
			$data = $form -> getData();

			if (!is_object($item))
			{
				$item = $table -> fetchNew();
				$item -> template_id = $id;
				$item -> language = $lang;
			}

			$item -> fromArray($data);
			
			$item -> save();
			
			$form -> setNotice('Saved Successful!');
			
			Response::redirect('admin/system/mail/template');
		}

		$request -> response = View::render($script = 'core/html/admin/edit', $data = array(
			'form' => $form,
			'title' => 'Edit Mail Template'
		));
	}

}
